package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;

import views.SelectedView;
import data.ShowData;

public class ImportHandler extends AbstractHandler
{
    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException
    {
        File file = openFileDialog();
        if (file == null)
            return null;

        SelectedView.getInstance().deleteAll();
        importShows(file);
        return null;
    }
    
    private File openFileDialog()
    {
        FileDialog fd = new FileDialog(Display.getCurrent().getShells()[0]);
        fd.setFilterExtensions(new String[]{"*.xml"});
        String fName = fd.open();
        if (fName == null)
            return null; 
        
        return new File(fName);
    }

    private void importShows(File file)
    {
        Properties p = new Properties();
        LinkedList<ShowData> shows = new LinkedList<ShowData>();
        try
        {
            p.loadFromXML(new FileInputStream(file));
            Set<Entry<Object, Object>> e = p.entrySet();
            for (Iterator iterator = e.iterator(); iterator.hasNext();)
            {
                Entry<Object, Object> entry = (Entry<Object, Object>) iterator
                        .next();
                String key = (String) entry.getKey();
                ShowData show = SageTvShows.getInstance().getShowByID(key);
                if (show == null)
                    continue;
                
                shows.add(show);
              //title,location,newname
                String value = (String) entry.getValue();
                String[] split = value.split(",");
                if (split.length > 2)
                {
                    show.setNewFileName(split[2]);
                }
            }
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        
        SelectedView.getInstance().addShows(shows);
    }
}
